package com.jiuxian.scheduling.listener.zk;

import com.jiuxian.scheduling.config.ConfigServer;
import com.jiuxian.scheduling.config.ConfigServerFactory;
import com.jiuxian.scheduling.tasks.SchedulerApplication;
import com.jiuxian.scheduling.vo.SchedingVO;
import org.I0Itec.zkclient.IZkChildListener;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.JobKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by wangjingqing on 2017/11/8.
 * 监听子节点增加和删除变化<br>
 * @author wangjingqing
 */
public class ZkChildListener implements IZkChildListener {

    private ConfigServer configServer = ConfigServerFactory.getConfigServer();
    Logger logger = LoggerFactory.getLogger(ZkChildListener.class);

    @Override
    public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
        logger.info("节点改变："+currentChilds);
        Set<String> containerName = new HashSet<>();
        List<JobKey> keys = SchedulerApplication.keys;
        if(CollectionUtils.isNotEmpty(keys)){
            keys.forEach(info->containerName.add(info.getName()));
        }
        Collection<String> junctList = CollectionUtils.disjunction(containerName, currentChilds);
        if(CollectionUtils.isNotEmpty(junctList)){
            junctList.forEach(info->{
                if(SchedulerApplication.containJob(info) && !currentChilds.contains(info)){
                    SchedulerApplication.removeJob(info);
                }else{
                    SchedingVO data = configServer.get(info);
                    if(data != null){
                        SchedulerApplication.addJob(data);
                    }else{
                        logger.info("{}节点信息不存在",info);
                    }
                }
            });
        }
    }
}
